const fs = require('node:fs');
const path = require('node:path');
const readline = require('node:readline');

const directoryPath = 'E:\\迅雷下载\\待处理剧集\\Y 星人儿歌之兔子贝贝\\Y 星人儿歌之兔子贝贝';

const resultPath = 'E:\\迅雷下载\\待处理剧集\\Y 星人儿歌之兔子贝贝\\resultPath';

// const oldFilePath = path.join(directoryPath, file)

const files = fs.readdirSync(directoryPath);
const dirLen = files.length;

let cp_info = [];

files.forEach(async item => {
  const dir = path.join(directoryPath, item);
  const dirFiles = fs.readdirSync(dir);

  const es = await new Promise(resolve => {
    const cfg = dirFiles.find(item => item.includes('.qiyicfg'));

    const fileStream = fs.createReadStream(dir + '\\' + cfg);
    const rl = readline.createInterface({
      input: fileStream,
      crlfDelay: Infinity
    });

    let lastLine = '';

    rl.on('line', line => {
      lastLine = line;
    });

    rl.on('close', () => {
      if (lastLine.indexOf('episode') > -1) {
        const es = lastLine.split('=')[1].trim();
        resolve(es);
      }
    });
  });

  const qsv = dir + '\\' + dirFiles.find(item => item.includes('.qsv'));

  const img = dir + '\\' + dirFiles.find(item => item.includes('img.') && !item.includes('h1'));

  const info = {
    es,
    qsv,
    img
  };
  // console.log(info)

  cp_info.push(info);

  if (cp_info.length >= dirLen) {
    copyFileArr(cp_info);
  }
});

function copyFileArr(cp_info) {
  let len = 0;

  cp_info.forEach(item => {
    const e = 'E' + item.es;
    copyFile(item.qsv, resultPath + '//' + e + '.mp4', err => {
      if (err) {
        console.error('复制文件时发生错误:', err);
      } else {
        console.log('文件复制成功！');
      }

      len++;

      if (len >= cp_info.length * 2) {
        console.log('全部复制成功！');
      }
    });

    const nfArr = item.img.split('.');

    const model = nfArr.length > 1 ? nfArr[nfArr.length - 1] : 'jpg';

    copyFile(item.img, resultPath + '//' + e + '-thumb.' + model, err => {
      if (err) {
        console.error('复制文件时发生错误:', err);
      } else {
        console.log('文件复制成功！');
      }
      len++;

      if (len >= cp_info.length * 2) {
        console.log('全部复制成功！');
      }
    });
  });
}

function copyFile(source, destination, callback) {
  console.log(source);
  fs.readFile(source, (err, data) => {
    if (err) {
      callback(err);
    } else {
      fs.writeFile(destination, data, err => {
        callback(err);
      });
    }
  });
}
